package com.gy.paidao.person;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gy.paidao.BaseActivity;
import com.gy.paidao.MainActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.person.bean.LoginBean;
import com.gy.paidao.util.KeyBoard;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.PhotoUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.SelectPicPopupWindow;
import com.gy.paidao.util.Urls;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.http.OkHeaders;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 作者：gy on 16/2/20
 * 说明：完成用户信息
 */
public class FinishProfileActivity extends BaseActivity{

    private ImageView imgHead;
    private EditText etName;
    private TextView tvComplete;
    private String strName;
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private File tempFile;// 创建一个以当前时间为名称的文件
    private Drawable drawable;
    private Bitmap bitmap;
    private String tempPath,lastPathSegment;
    private Uri photoUri;// 照片uri
    private SelectPicPopupWindow selectPic;
    private int userId;
    private String strEmial,strCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finish_profile);
        setViews();
    }

    @Override
    protected void initVariable() {
        userId = getIntent().getIntExtra("userId", 0);
        strEmial = getIntent().getStringExtra("userId");
        strCode = getIntent().getStringExtra("code");
    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        imgHead = (ImageView) findViewById(R.id.activity_finish_profile_img_head);
        etName = (EditText) findViewById(R.id.activity_finish_profile_et_name);
        tvComplete = (TextView) findViewById(R.id.activity_finish_profile_tv_complete);

        imgHead.setOnClickListener(this);
        tvComplete.setOnClickListener(this);
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId){
            case R.id.activity_finish_profile_tv_complete:
                strName = etName.getText().toString().trim();
                lastPathSegment = "photo";
                if(TextUtils.isEmpty(strName)){
                    showToast("请输入用户名");
                } else {
                    KeyBoard.demissKeyBoard(this, etName);
                    if(bitmap == null){
                        showToast("请上传头像");
                    }else {
                        dorequestComplete();
                    }
                }
                break;
            case R.id.activity_finish_profile_img_head:
                selectPic = new SelectPicPopupWindow(this,itemsOnClick);
                tempFile = new File(getPhotoFileName());
                selectPic.showAtLocation(this.getWindow().getDecorView(),
                        Gravity.CENTER, 0, 0);

                break;
        }
    }

    private void dorequestComplete(){
        showLoading();
        final OkHttpClient client = new OkHttpClient();
        client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.setWriteTimeout(30, TimeUnit.SECONDS);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        RequestBody fileBody = null;
        fileBody = RequestBody.create(MediaType.parse(guessMimeType(lastPathSegment)), b);
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart("userId", userId+"")
                .addFormDataPart("nickname", strName+"")
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";" +
                        "filename=\"" + lastPathSegment + "\""), fileBody);
        final Request request = new Request.Builder()
                .url(Urls.url_common+"/user/completeProfile")
                .post(multipartBuilder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                LogUtil.e("头像上传失败");
                dismissLoading();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                CookieHandler cookieHandler = client.getCookieHandler();
                if (cookieHandler != null) {
                    Map<String, List<String>> headers = OkHeaders.toMultimap(request.headers(), null);
                    Map<String, List<String>> cookies = cookieHandler.get(request.uri(), headers);
                    for (String key : cookies.keySet()) {
                        String cookie = cookies.get(key).get(0);
                        if(cookie.indexOf("userLoginID=") != -1){
                            cookie = cookie.substring(12,cookie.length());
                            LogUtil.e("cookie="+cookie);
                            SPHelper.getInstance(FinishProfileActivity.this).setStringData("userLoginID",cookie);
                        }
                    }
                }

                String json = response.body().string();
                LogUtil.e("头像上传成功"+json);
                dismissLoading();
                BaseBean baseBean = gson.fromJson(json,BaseBean.class);
                if(baseBean.success){
                    LoginBean bean = gson.fromJson(json,LoginBean.class);
                    MyApplication.loginBean = bean;
                    MyApplication.USERID = bean.id;
                    Intent intent = new Intent(FinishProfileActivity.this, MainActivity.class);
                    FinishProfileActivity.this.startActivity(intent);
                    setResult(101);
                    FinishProfileActivity.this.finish();
                } else {
                    if(!TextUtils.isEmpty(baseBean.errMsg)){
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = baseBean.errMsg;
                        toastHandler.sendMessage(msg);
                    }
                }
            }
        });
    }

    private Handler toastHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String toast = (String) msg.obj;
            showToast(toast);
        }
    };

    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            selectPic.dismiss();
            Intent intent;
            switch (v.getId()) {
                case R.id.pop_select_picture_ll_take:
                    // 调用系统的拍照功能
                    // startCamera();
                    // 调用系统的拍照功能
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 指定调用相机拍照后照片的储存路径
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                    break;
                case R.id.pop_select_picture_ll_pick:
                    // selectPictrue();
                    intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch (requestCode) {
            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
            case PHOTO_REQUEST_TAKEPHOTO:
                if (tempFile == null) {
                    showToast("操作失败,请重试...");
                    return;
                }
                tempPath = tempFile.getPath();
                tempFile = null;
                int degree = getBitmapDegree(tempPath);
                bitmap = PhotoUtil.getSizedBitmap(1280, 720, tempPath);
                if(bitmap == null)
                    return;
                bitmap = rotateBitmapByDegree(bitmap, degree);
                if (bitmap != null) {
                    imgHead.setImageBitmap(bitmap);
//                    addPicture(bitmap);
                }
                break;

            case PHOTO_REQUEST_GALLERY:
                setImageProve(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            bitmap = photo;
            drawable = new BitmapDrawable(photo);
            imgHead.setImageDrawable(drawable);
//            addPicture(bitmap);
        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path
     *            图片绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm
     *            需要旋转的图片
     * @param degree
     *            旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private void setImageProve(Intent data) {
        if (data == null) {
            showToast("操作失败,请重试...");
            return;
        }
        photoUri = data.getData();
        try {
            ContentResolver resolver = getContentResolver();

            if (resolver.getType(photoUri) != null
                    && PhotoUtil.isImageFormat(resolver.getType(photoUri))) {

            } else {
                showToast("操作失败,请重试...");
                return;
            }
            Cursor cursor = this.getContentResolver().query(photoUri, null,
                    null, null, null);
            cursor.moveToFirst();
            String path = "";
            try {
                path = cursor.getString(1);
            } catch (Exception e) {
            }
            cursor.close();
            if (PhotoUtil.isImageFormat(resolver.getType(photoUri))) {
            } else {
                InputStream in = resolver.openInputStream(photoUri);
            }
            int degree = getBitmapDegree(path);
            bitmap = PhotoUtil.getSizedBitmap(1280, 720, path);
            if(bitmap == null)
                return;
            bitmap = rotateBitmapByDegree(bitmap, degree);
            imgHead.setImageBitmap(bitmap);
//            addPicture(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("操作失败,请重试...");
            return;
        }
        tempPath = photoUri.getPath();
        if (tempPath == null) {
            showToast("操作失败,请重试...");
            return;
        }
        if (tempPath.endsWith(".jpg") || tempPath.endsWith(".png")
                || tempPath.endsWith(".jpeg")) {

        } else if (!tempPath.startsWith("/mnt/")) {
            String[] proj = { MediaStore.Images.Media.DATA };
            // Sysout.i("img path ===", tempPath);
            Cursor actualimagecursor = managedQuery(photoUri, proj, null, null,
                    null);
            if (actualimagecursor != null) {
                int actual_image_column_index = actualimagecursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                tempPath = actualimagecursor
                        .getString(actual_image_column_index);
            } else {
                showToast("操作失败,请重试...");
                return;
            }
        }
    }

    private String getPhotoFileName() {

        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return "/storage/emulated/0/Android/data/com.gy.paidao/files/mounted/qupaiVideo/"+ dateFormat.format(date) + ".jpg";
    }

}
